from django.core.mail import send_mail
from django.http import HttpResponseRedirect
from django.shortcuts import render_to_response
from t6.books.forms import ContactForm, AuthorForm
from t6.books.models import Book, Author

def search_form(request):
    return render_to_response('search_form.html')

def search(request):
    errors = []
    if 'q' in request.GET:
        q = request.GET['q']
        if not q:
            errors.append('Enter a search term.')
        elif len(q) > 20:
            errors.append('Please enter at most 20 characters.')
        else:
            books = Book.objects.filter(title__icontains=q)
            return render_to_response('search_results.html',
                {'books': books, 'query': q})
    return render_to_response('search_form.html', {'errors': errors })

def contact(request):
    if request.method == 'POST':
        form = ContactForm(request.POST)
        if form.is_valid():
            cd = form.cleaned_data
            send_mail(
                cd['subject'],
                cd['message'],
                cd.get('email', 'honglang_j@163.com'),
                ['sunson_jhl@163.com'],
            )
            return HttpResponseRedirect('/contact/thanks/')
    else:
        form = ContactForm(initial={'subject': 'I love your site!'})
    return render_to_response('contact_form.html', {'form': form})

def auth_list(request):
    auths = Author.objects.all()
    return render_to_response('auths/auth_list.html', {'form':auths, 'list':auths})
    
def auth_add(request):
    if request.method == 'POST':
        form = AuthorForm(request.POST)
        if form.is_valid():
            model = Author(first_name=request.POST.get('first_name', ''),
                           last_name=request.POST.get('last_name', ''),
                           email=request.POST.get('email', ''))
            model.save()
            auths = Author.objects.all()
            return render_to_response('auths/auth_list.html', {'form':auths, 'list':auths})
    else:
        #initial={'first_name': 'enter your first name','last_name':'enter your last name','email':'enter your email'}
        initial={}
        form = AuthorForm(initial)
    return render_to_response('auths/auth_add.html',{'form':form})
